/**
 * @fileOverview    路由入口.
 * @author          shaozhe.ysz@alibabapictures.com
 * @since           2016.07.28
 */

var express = require('express'),
    router = express.Router(),
    c = require('./c'),
    debug = require('./debug'),
    {getPaths,getFiles} = require('./file'),
    combo = require('./combo');

const TypeMap = {
    css:/css/,
    html:/text\/html/,
    js:/.*/
}

var Log = function(init = ''){
    var logContent = init;

    this.log = (s)=>{logContent+=(s+'\n');return this;}
    this.print = ()=>{console.log(logContent);return this;}
};

router.get(/.*/, function (req, res) {

    let type = req.headers.accept,
        log = new Log(),
        key;
    for(key in TypeMap){
        if(TypeMap[key].test(type)){
            res.type(key);
            break;
        }
    };

    //拆解请求。
    log.log('\n' + c.cyan('GET '+key + ':') + req.protocol + '://' + req.hostname + req.originalUrl);

    getPaths.bind(log)(req.originalUrl,req.hostname,req.protocol)
        .then(paths=>getFiles.bind(log)(paths))
        .then(files=>combo.bind(log)(files))
        .then((file)=>{
            res.send(file);
            log.print();
        })
        .catch(err=>{
            log.log(err||'\x1b[31mERROR\x1b[0m');
            log.print();
        });

});

module.exports = router;